package com.cloudinnov.task;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cloudinnov.logic.HistoryDataLogic;
import com.cloudinnov.utils.PropertiesUtils;
import com.cloudinnov.utils.support.spring.SpringUtils;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;


/** 告警规则任务处理
 * @ClassName: AlarmRuleQuartzJob 
 * @Description: TODO
 * @author: ningmeng
 * @date: 2016年12月1日 下午2:00:24  
 */
public class AlarmRuleQuartzJob {
	
	private static final Logger logger = LoggerFactory.getLogger(AlarmRuleQuartzJob.class);
	
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH");
	private SimpleDateFormat sdfSql = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private JedisPool jedisPool = SpringUtils.getBean("jedisPool");
	private static final String POINT_NAME = "point:";
	private static final String VALUE_NAME = ":value";
	private static final String HISTORY_RECORD_KEY_NAME = "history_record";
	private static final int POINT_NAME_SPLITTER_LEVEL1 = 1;
	private static final int TIME_SPLITTER_LEVEL1 = 2;
	private static final String HISTORY_SPLITTER_LEVEL1 = ":";
	private static final String REGULAR_VALUE = "*";
	
	private HistoryDataLogic historyDataLogic = SpringUtils.getBean("historyDataLogic");

	/**
	 * 任务调度 去消费历史数据并且插入数据库 execute
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param 参数
	 * @return void 返回类型
	 * @throws ParseException
	 */
	protected void execute() throws ParseException {
		Calendar cal = Calendar.getInstance();
		long start = System.currentTimeMillis();
		logger.debug("----历史定时处理服务开始启动----     " + sdfSql.format(cal.getTime()));
		Jedis redis = null;
		try {
			redis = jedisPool.getResource();
			// 获取所有历史数据key
			Set<String> historykeys = redis
					.keys(POINT_NAME + REGULAR_VALUE + HISTORY_SPLITTER_LEVEL1 + REGULAR_VALUE + VALUE_NAME);
			// point:ADYSdp4z:value:prevent
			int i = 0;
			if (historykeys != null) {
				for (String point : historykeys) {
					List<String> list = new ArrayList<String>();
					redis.select(Integer.parseInt(PropertiesUtils.findPropertiesKey("redis.db.pointvalue")));
					list = redis.lrange(point, 0, -1);
					if(list!=null && list.size()>0){
						String compressedValue = compressed(list);
						cal.setTime(sdf.parse(point.split(HISTORY_SPLITTER_LEVEL1)[TIME_SPLITTER_LEVEL1]));
						Map<String, Object> map = new HashMap<String, Object>();
						map.put("pointCode", point.split(HISTORY_SPLITTER_LEVEL1)[POINT_NAME_SPLITTER_LEVEL1]);
						map.put("value", compressedValue);
						map.put("time", sdfSql.format(cal.getTime()));
						int returnCode = historyDataLogic.insert(map);
						if (returnCode > 0) {
							redis.select(Integer.parseInt(PropertiesUtils.findPropertiesKey("redis.db.record")));
							redis.sadd(HISTORY_RECORD_KEY_NAME, point);// 已经处理的存入到消费记录库中，保证只消费一次
							redis.select(Integer.parseInt(PropertiesUtils.findPropertiesKey("redis.db.pointvalue")));
							redis.del(point);
						}
						logger.debug("点位: " + point.split(HISTORY_SPLITTER_LEVEL1)[POINT_NAME_SPLITTER_LEVEL1]
								+ "\r\n入库成功,返回值为: " + returnCode + "\r\n时间为:"
								+ point.split(HISTORY_SPLITTER_LEVEL1)[TIME_SPLITTER_LEVEL1]);
						i++;
					}
				}
			}
			logger.debug("------------历史定时处理服务处理完毕---------------  处理" + i + "条 -----共 耗时(s)"
					+ (System.currentTimeMillis() - start) / 1000);
		} catch (Exception e) {
			logger.error("历史定时处理服务 \r{}", e);
		} finally {
			jedisPool.returnResource(redis);
		}
	}
	public List<String> readFromRedis(String pointCode, Calendar calendar, Jedis jedis) {
		StringBuilder sb = new StringBuilder();
		sb.append(POINT_NAME).append(pointCode).append(sdf.format(calendar.getTime())).append(VALUE_NAME);
		List<String> list = new ArrayList<String>();
		list = jedis.lrange(sb.toString(), 0, -1);
		return list;
	}
	public int writeToMysql(String point, String value, Calendar calendar) {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		int result = 0;
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			conn = DriverManager.getConnection("jdbc:mysql://localhost/chengning", "root", "root");
			ps = conn.prepareStatement(
					"insert into iot_temp(iot_temp_point_id, iot_temp_ts, iot_temp_value) values(?,?,?)");
			ps.setString(1, point);
			ps.setString(2, sdfSql.format(calendar.getTime()));
			ps.setString(3, value);
			result = ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				ps.close();
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return result;
	}
	public String getPointValues(String point, Date start, Date end) {
		StringBuilder sb = new StringBuilder();
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			conn = DriverManager.getConnection("jdbc:mysql://localhost/chengning", "root", "root");
			ps = conn.prepareStatement(
					"SELECT iot_temp_value FROM iot_temp where iot_temp_point_id =? and iot_temp_ts >=? and iot_temp_ts <=?");
			ps.setString(1, point);
			ps.setString(2, sdfSql.format(start));
			ps.setString(3, sdfSql.format(end));
			rs = ps.executeQuery();
			while (rs.next()) {
				String values = rs.getString("iot_temp_value");
				String[] fields = values.split(";");
				for (String field : fields) {
					Date date = new Date(Long.parseLong(field.split(",")[0]));
					if (date.after(start) && date.before(end)) {
						sb.append(field).append(";");
					}
				}
			}
			if (sb.length() > 1)
				sb.deleteCharAt(sb.length() - 1);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				ps.close();
				rs.close();
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}
	public static void main(String[] args) {
		AlarmRuleQuartzJob main = new AlarmRuleQuartzJob();
		String pointId = "X1001-YY-2";
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - 1);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MILLISECOND, 0);
		// List<String> list = main.readFromRedis(pointId, calendar,);
		// String compressedValue = compressed(list);
		// main.writeToMysql(pointId, compressedValue, calendar);
		Date start = calendar.getTime();
		calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) + 1);
		Date end = calendar.getTime();
		System.out.println(main.getPointValues(pointId, start, end));
	}
	private static String compressed(List<String> list) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < list.size(); i++) {
			sb.append(list.get(i));
			if (i != list.size() - 1)
				sb.append(";");
		}
		return sb.toString();
	}
}
